package com.xidian.zhiancloud.controller.systemset;

import com.github.pagehelper.Page;
import com.xidian.zhiancloud.controller.base.BaseController;
import com.xidian.zhiancloud.dto.ResultDTO;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.enums.UserResponseEnums;
import com.xidian.zhiancloud.model.syset.DepartList;
import com.xidian.zhiancloud.model.syset.ImportUser;
import com.xidian.zhiancloud.model.syset.JobList;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.BaseReqQuery;
import com.xidian.zhiancloud.service.user.UserService;
import com.xidian.zhiancloud.util.api.ExcelUtil2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

	private final static Logger logger = LoggerFactory.
            getLogger(UserController.class);
	
	@Autowired
	UserService userService;
	
	/**
     *  -用户登录
     * @param username
     * @param password 
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping(value = "/login")
    public ResultDTO login
		(@RequestParam("username") String username,
		 @RequestParam("password") String password ) {
            if(password == null || password.length() < 3){
                return ResultDTO.errorOf
					(UserResponseEnums.PASSWORD_LESS_THAN_SIX);
            }
            SysUser user = userService.Login(username, password);
            System.out.println(" user : " + user);
            if (user == null) {
                return ResultDTO.errorOf(UserResponseEnums.USER_NOT_FOUND);
            }
            this.saveSessionUser(user);
            Map<String, Object> data = new HashMap<String, Object>();
    		data.put("user", user);
    		data.put("sessionId", getSessionId());
        return ResultDTO.successOf(data, GeneralResponseEnums.SUCCESS);
    }
	/**
     *  -用户列表
     * @param reqdata
     * @param params 多个参数集合
     * @return 返回 ResultDTO 对象
     */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/getUserList")
	public ResultDTO getUserList
		(BaseReqQuery reqdata,
		@RequestParam(value="jobid",required=false ,defaultValue="0")
			Integer jobid,
		@RequestParam(value="departid",required=false ,defaultValue="0")
			Integer departid,
		@RequestParam(value="orgid",required=false ,defaultValue="0")
			Integer orgid,
		@RequestParam(value="roleid",required=false ,defaultValue="0")
			Integer roleid) {/*
		if(jobid<=0)
		{
			jobid = getSessionDepartid();
		}
		*/
		logger.info("jobid :" + jobid);
		Page<SysUser> pagedata = userService.getUserList
				(orgid,departid,jobid,roleid, reqdata);
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("datalist", pagedata);
		data.put("PageNum", pagedata.getPageNum());
		data.put("PageSize", pagedata.getPageSize());
		data.put("PageTotal", pagedata.getPages());
		data.put("total", pagedata.getTotal());
		return ResultDTO.successOf(data,GeneralResponseEnums.SUCCESS);
	}
	/**
     *  -导出用户列表
     */
	@GetMapping("/exportUser")
    public void export(HttpServletResponse response,BaseReqQuery reqdata,
		@RequestParam(value="jobid",required=false ,defaultValue="0")
				Integer jobid,
		@RequestParam(value="departid",required=false ,defaultValue="0")
				Integer departid,
		@RequestParam(value="orgid",required=false ,defaultValue="0")
				Integer orgid,
		@RequestParam(value="roleid",required=false ,defaultValue="0")
				Integer roleid) throws IOException {
       // List<SysUser> list = userService.selectUserList();
		logger.info("jobid :" + jobid);
		reqdata.setPageSize(9999999);
		Page<SysUser> pagedata = userService.getUserList
				(orgid,departid,jobid,roleid, reqdata);
		List<SysUser> list = pagedata.getResult();
        ExcelUtil2<SysUser> util = new ExcelUtil2<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }
	
	 @PostMapping("/importData")
		public ResultDTO importData
			 (MultipartFile file, boolean updateSupport) throws Exception {
			ExcelUtil2<SysUser> util = new ExcelUtil2<SysUser>(SysUser.class);
			List<SysUser> userList = util.importExcel(file.getInputStream());
			//String message = userService.importUser(userList, updateSupport);
			return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
		}
	
	/**
     *  -新增用户
	 *
	 * @param id 用户ID
	 * @param username //昵称
     * @param phone //手机号
     * @param name 	//名称
	 * @param password //密码
     * @param orgids     //  部门
     * @param departids  //  岗位
     * @param jobids     //  职位
     * @param roleids    角色ID
     * @param major     //专业
     * @param jobnum //工号
     * @param idnum  //身份证号 
     * @param age;      //年龄
	 * @param gender;   //性别  1 男， 2 女
	 * @param  email; 	电子邮箱
	 * @param  entrydatetime; //入职时间
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping(value = "/addUser")
	public ResultDTO AddUser (SysUser userdata) {
		if(userdata.getPhone().length()!=11||
			userdata.getName().length()<1||
			userdata.getDepartids().length()<1||
			userdata.getRoleids().length()<1) {
			return ResultDTO.errorOf(UserResponseEnums.USER_PARAMETERS_ERROR);
		}
		if(userdata.getCompanyid()==null||userdata.getCompanyid()<1) {
			userdata.setCompanyid(this.getSessionUserCompanyId());
		}
		int rt = userService.insertUser(userdata);
		if(rt!=1) {
			return ResultDTO.errorOf(UserResponseEnums.USER_PARAMETERS_ERROR);
		}
		return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
	}
	/**
     *  -组织层级列表
     * @param 
     * @param 
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getOrgLeveList")
	public ResultDTO getOrgLeveList() {
        Long companyId = this.getSessionUserCompanyId();
		return ResultDTO.successOf(userService.getOrgLeveList(companyId),
				GeneralResponseEnums.SUCCESS);
	}
	
	/**
     *  -组织机构列表
     * @param 
     * @param 
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getOrgList")
	public ResultDTO getOrgList() {
        Long companyId = this.getSessionUserCompanyId();
		return ResultDTO.successOf(userService.getOrgList(companyId),
				GeneralResponseEnums.SUCCESS);
	}
	
	
	/**
     *  - 职位列表
     * @param reqdata
     * @param
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getJobList")
	public ResultDTO getJobList(BaseReqQuery reqdata) {
        Long companyId = this.getSessionUserCompanyId();
		Page<JobList> pagedata = userService.getJobList(companyId,reqdata);
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("datalist", pagedata);
		data.put("PageNum", pagedata.getPageNum());
		data.put("PageSize", pagedata.getPageSize());
		data.put("PageTotal", pagedata.getPages());
		data.put("total", pagedata.getTotal());
		return ResultDTO.successOf(data,GeneralResponseEnums.SUCCESS);
	}
	
	/**
     *  - 岗位列表
     * @param reqdata 参数集合
     * @param orgid 组织结构ID
	 * @param jobid 职位ID
	 * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getDepartList")
	public ResultDTO getDepartList(BaseReqQuery reqdata,
		@RequestParam(value="orgid",required=false ,defaultValue="0")
				Integer orgid,
		@RequestParam(value="jobid",required=false ,defaultValue="0")
				Integer jobid){
        Long companyId = this.getSessionUserCompanyId();
		Page<DepartList> pagedata = userService.getDepartList
				(companyId,reqdata,orgid,jobid);
		
		Map<String, Object> data = new HashMap<String, Object>();
		data.put("datalist", pagedata);
		data.put("PageNum", pagedata.getPageNum());
		data.put("PageSize", pagedata.getPageSize());
		data.put("PageTotal", pagedata.getPages());
		data.put("total", pagedata.getTotal());
		return ResultDTO.successOf(data,GeneralResponseEnums.SUCCESS);
	}
	//List<RoleList> getRoleList()
	
	/**
     *  - 角色列表
     * @param 
     * @param
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getRoleList")
	public ResultDTO getRoleList() {
		return ResultDTO.successOf(userService.getRoleList(),
				GeneralResponseEnums.SUCCESS);
	}
	
	/**
     *  - 获取设置菜单列表
     * @param 
     * @param
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getMenuRightByRoleid")
	public ResultDTO getMenuRightByRoleid(Integer roleid) {
		return ResultDTO.successOf(userService.getMenuRightByRoleid(roleid),
				GeneralResponseEnums.SUCCESS);
	}
	/**
     *  - 获取登录用户的菜单
     * @param 
     * @param
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getMenuByRoleid")
	public ResultDTO getMenuByRoleid
		( @RequestParam(value="defant", required=false ,defaultValue="0")
					Integer defant) {
		if(defant ==1){
			return ResultDTO.successOf(userService.getMenuByAdmin(defant),
					GeneralResponseEnums.SUCCESS);
		}
		String roleids = this.getSessionRoleid();
		return ResultDTO.successOf(userService.getMenuByRoleid(roleids),
				GeneralResponseEnums.SUCCESS);
	}
	/**
     *  - 获取所有的菜单
     * @param 
     * @param
     * @return 返回 ResultDTO 对象
     */
	@RequestMapping("/getMenuByAdmin")
	public ResultDTO getMenuByAdmin(){
		int defant = 0;
		return ResultDTO.successOf(userService.getMenuByAdmin(defant),
				GeneralResponseEnums.SUCCESS);
	}

	/**
	 * 删除用户
	 * @param id 用户ID
	 * @return 返回 ResultDTO 对象
	 */
	@RequestMapping("/deletByUserId")
	public ResultDTO deletByUserId(@RequestParam("id") String id){
		userService.deletByUserId(id);
		return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
	}

	/**
	 * 编辑组织层级
	 * @param id 组织层级ID
	 * @param customtypename 组织层级自定义名称
	 * @return 返回 ResultDTO 对象
	 */
	@RequestMapping("/updateByOrgLevelId")
	public ResultDTO updateByOrgLevelId(@RequestParam("id") String id,
			@RequestParam("customtypename") String customtypename){
		userService.updateByOrgLevelId(id,customtypename);
		return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
	}

	/**
	 * 删除职位
	 * @param id 职位ID
	 * @return 返回 ResultDTO 对象
	 */
	@RequestMapping("/deletByJobId")
	public ResultDTO deletByJobId(@RequestParam("id") String id){
		userService.deletByJobId(id);
		return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
	}

	/**
	 * 添加职位
	 * @param job 职位信息
	 * @return 返回ResultDTO 对象
	 */
	@RequestMapping("/addJobMes")
	public ResultDTO addJobMes(JobList job){
        Long companyId = this.getSessionUserCompanyId();
			job.setCompanyId(companyId);
			job.setCreateuserid(this.getSessionUserid().intValue());
//			JobList jobs=userService.getByJobAndIdAndName(companyId,job.getName());
//            if(jobs==null){
//                userService.addJobMes(job);
//            }else if(jobs!=null){
//                return ResultDTO.errorOf(UserResponseEnums.JOB_ALREADY_EXISTS);
//            }
		return ResultDTO.successOf(userService.addJobMes(job),
            GeneralResponseEnums.SUCCESS);
	}

	/**
	 * 编辑职位
	 * @param id 职位ID
	 * @param num 职位顺序
	 * @param name 职位名称
	 * @return
	 */
	@RequestMapping("/updateJobMes")
	public ResultDTO updateJobMes
		(@RequestParam("id") String id,
		 @RequestParam("num") Integer num,
		 @RequestParam("name") String name){
//        JobList jobs=userService.getByJobAndIdAndName
//        (this.getSessionUserCompanyId(),name);
//        if(jobs==null && !id.equals(jobs.getId())){
//            userService.updateJobMes(id,num,name);
//        }else if(jobs!=null && id.equals(jobs.getId())){
//            return ResultDTO.errorOf(UserResponseEnums.JOB_ALREADY_EXISTS);
//        }
        int createId = this.getSessionUserid().intValue();
		return ResultDTO.successOf(userService.updateJobMes(id,num,name,createId),GeneralResponseEnums.SUCCESS);
	}

	/**
	 *  编辑用户
	 * @param id 用户ID
	 * @return 返回ResultDTO对象
	 */
	@RequestMapping("/updateUser")
	public ResultDTO updateUser(SysUser userdata, @RequestParam
			(value = "id",required = false,defaultValue = "0") String id){
		if(userdata.getPhone().length()!=11||userdata.getName().length()<1||
			userdata.getDepartids().length()<1||userdata.getRoleids().length()<1){
			return ResultDTO.errorOf(UserResponseEnums.USER_PARAMETERS_ERROR);
		}
		if(userdata.getCompanyid()==null||userdata.getCompanyid()<1) {
			userdata.setCompanyid(this.getSessionUserCompanyId());
		}
		int rt = userService.updateUser(id,userdata);
		if(rt!=1) {
			return ResultDTO.errorOf(UserResponseEnums.USER_PARAMETERS_ERROR);
		}
		return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
	}

	@PostMapping("/importUserData")
	public ResultDTO importUserData
			(MultipartFile file, boolean updateSupport) throws Exception {
		Long companyId = this.getSessionUserCompanyId();
		ExcelUtil2<ImportUser> util = new ExcelUtil2<ImportUser>(ImportUser.class);
		List<ImportUser> userList = util.importExcel(file.getInputStream());
		String message = userService.importUserData(companyId,userList, updateSupport);
		return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
	}

    /**
     * 添加岗位
     * @param depart 岗位
     * @return 返回 ResultDTO 对象
     */
    @RequestMapping("/addDepart")
    public ResultDTO addDepart(DepartList depart){
        Long companyId = this.getSessionUserCompanyId();
        depart.setCompanyId(companyId.intValue());
//        DepartList departs = userService.getByDepartAndIdAndName
//        (companyId, depart.getName());
//        if(departs==null){
//            userService.addDepart(depart);
//        }else if(departs!=null){
//            return ResultDTO.errorOf(UserResponseEnums.DEPART_ALREADY_EXISTS);
//        }
        return ResultDTO.successOf(userService.addDepart(depart),GeneralResponseEnums.SUCCESS);
    }

    /**
     * 编辑岗位
     * @param id 岗位ID
     * @param depart 岗位
     * @return 返回 ResultDTO 对象
     */
    @RequestMapping("/updateDepart")
    public ResultDTO updateDepart(@RequestParam("id") String id,DepartList depart){
        Long companyId = this.getSessionUserCompanyId();
        depart.setCompanyId(companyId.intValue());
//        DepartList departs = userService.getByDepartAndIdAndName
//        (companyId, depart.getName());
            userService.updateDepart(id,depart);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 删除岗位
     * @param id 岗位ID
     * @return 返回 ResultDTO 对象
     */
    @RequestMapping("/deleteDepart")
    public ResultDTO deleteDepart(@RequestParam("id") String id){
        userService.deleteDepart(id);
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

    /**
     * 登录忘记密码
     * @param phone 手机号
     * @param newPassword 密码
     * @return 返回ResultDTO对象
     */
    @RequestMapping("/updateByPassword")
    public ResultDTO updateByPassword(@RequestParam("phone") String phone,
              @RequestParam("newPassword") String newPassword){
        Long companyId = this.getSessionUserCompanyId();
        List<SysUser> userList = userService.getUserPhonle(companyId,phone);
            if(userList.size()>0){
                userService.updateByPassword(String.valueOf(userList.get(0).getId()),newPassword);
            }
        return ResultDTO.successOf(GeneralResponseEnums.SUCCESS);
    }

}



